<template>
    <n-space>
        <n-select v-model:value="seletedDevicePath" style="width:200px" @on-change="pathChanged" :options="lstUsbDevices"></n-select>
        <n-button @click="refreshUsbDevices" :disabled="bRefreshingUsb">刷新</n-button>
    </n-space>
</template>

<script lang="ts" setup>
import {ref, reactive} from 'vue'

import ChromeSerialSocket from '@beshell/conn-ts/ChromeSerialSocket'
// import SocketConnection, { ConnectionStatus, ab2str } from '@beshell/conn-ts/SocketConnection'



const bRefreshingUsb = ref(false)
const lstUsbDevices: any[] = reactive([])
const seletedDevicePath = ref("")


async function refreshUsbDevices() {

    bRefreshingUsb.value = true
    let oldSelectedPath = seletedDevicePath.value
    seletedDevicePath.value = ""

    // 清空
    lstUsbDevices.length = 0

    // 加载                
    for(let dev of await ChromeSerialSocket.getDevices()) {
        lstUsbDevices.push({
            label: `${dev.displayName.substr(0,20)} ${dev.displayName.length>20?'...':''} (${dev.path})`,
            value: dev.path
        })

        if(dev.path == oldSelectedPath) {
            seletedDevicePath.value = oldSelectedPath
        }
    }

    if(!seletedDevicePath.value && lstUsbDevices.length)
        seletedDevicePath.value = lstUsbDevices[0].value
    
    pathChanged()
    
    bRefreshingUsb.value = false
}

function pathChanged() {
    emit("input", seletedDevicePath.value)
}

const emit = defineEmits(["input"])

defineExpose({
    refreshUsbDevices
})
</script>